<?php

/**
 * Mailer CLI controller.
 *
 * @version $Id$
 * @package Application
 */

class Controller_Cli_Mailer extends Controller_Cli
{
	private $fp;

	public function before()
	{
		parent::before();
		set_time_limit(2000);
		$this->model = Model::factory('mailList');
	}


	private function log($message, $success = true, $end = false) {
		$text = '['.date('m/d/Y H:i').'] - ' . (($success) ? 'SUCCESS: ' : 'FAILURE: ') . $message . chr(10) . chr(13);
		if ($end) {
			$text .= "\n------------------------------------------------------------------\n\n";
		}
		fwrite($this->fp, $text);
	}

	public function actionIndex()
	{
		// Check file lock (if only one instance of run task is allowed)
		if ($this->fp = fopen('_logs/cli-mailer.txt', 'a')) {
			if (false == flock($this->fp, LOCK_EX | LOCK_NB)) {
				return;
			}
		}
		$cnt = 0;
		foreach (($messages = Database::instance()->query('SELECT * FROM `mailListMessages` WHERE `status` = "pending"')->fetchAll()) as $message) {
			$mail = new Mailer();
			foreach (($attachments = $this->model->getAttachments($message['id'])) as $attachment) {
				$mail->attachment('content/maillist/attachments/' . $message['id'] . '/' . $attachment['alias'] . '/' . $attachment['filename']);
			}
			$mail->from = $this->settings['email'];
			$mail->subject = $message['subject'];
			$mail->message(array('html' => new View('cli/message', array('message' => $message['message']))));
			$subscribers = $this->model->getSubscribersById();
			foreach (($recipients = Database::instance()->query('SELECT * FROM `mailListRecipients` WHERE `sent` = 0 AND `messageId` = ?', $message['id'])) as $recipient) {
				if (isset($subscribers[$recipient['subscriberId']])) {
					$mail->to = $subscribers[$recipient['subscriberId']]['email'];
				} else {
					$this->log('Subscriber with id="' . $recipient['subscriberId'] . '" not found.', false);
					continue;
				}
				$mail->send();
				Database::instance()->query('UPDATE `mailListRecipients` SET `sent` = 1 WHERE `subscriberId` = ? AND `messageId` = ?', array($message['id'], $recipient['subscriberId']));
				$cnt++;
				usleep(500000);
			}
			Model_Table::instance('mailListMessages')->update(array('status' => 'sent'), (int)$message['id']);
		}
		if ($cnt > 0) {
			$this->log('Mailer finished. ' . $cnt .' messages has been sent.', true, true);
		}
		// Release lock
		if (false == empty($this->fp)) {
			fclose($this->fp);
		}
	}

	public function actionTest()
	{
		if ($this->fp = fopen('_logs/cli-mailer.txt', 'a')) {
			if (false == flock($this->fp, LOCK_EX | LOCK_NB)) {
				return;
			}
		}
		fwrite($this->fp, 'ok');
		if (false == empty($this->fp)) {
			fclose($this->fp);
		}
	}
}